#! /bin/bash
# Call this script to format every c[pp] & h[pp] file
# in the parent directory using clang-format
#
# Returns
# 0 on success
# 2 is clang-format 8 could not be found 

# Detect clang-format version
if command -v clang-format-8 > /dev/null; then
    BINARY="clang-format-8"
elif command -v clang-format > /dev/null; then
    BINARY="clang-format"
    VERSION=$(clang-format --version | grep -o '[0-9]\+.[0-9]\+.[0-9]\+' | head -1 | cut -d '.' -f 1)
    if (( $VERSION != 8 )); then
        echo "clang-format version 8 expected, but ${VERSION} found!"
        echo "Please install a suffixed binary (clang-format-8) or install clang-format version 8."
        exit 2
    fi
else
    echo "clang-format not found!"
    echo "Please install clang-format version 8."
    exit 2
fi
echo "Using binary: $BINARY"

# Detect GNU parallel
if command -v parallel > /dev/null ; then
    echo "GNU parallel detected."
    HAS_PARALLEL=true
else
    echo "Install GNU parallel to format in parallel."
    HAS_PARALLEL=false
fi

# Format C/C++
CFILES=$(find . -type f -name \*.hpp -or -name \*.h -or -name \*.cpp -or -name \*.c)
echo "Formatting $(echo "$CFILES" | wc -l) C/C++ files"
if  $HAS_PARALLEL; then
    echo "$CFILES" | parallel --bar "${BINARY} -style=file -i {}"
else
    for cfile in $CFILES; do
        ${BINARY} -style=file -i $cfile
        echo -n "."
    done
    echo
fi

# Detect python3
SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
if command -v python3 > /dev/null; then
  PYCMD="python3"
else
  PYCMD="python"
fi

XMLFILES=$(find . -not \( -path ./docs -prune \) -type f -name \*.xml)
XMLFMT="$SCRIPTDIR/config-formatter"
echo "Formatting $(echo "$XMLFILES" | wc -l) XML files"
if $HAS_PARALLEL; then
    echo "$XMLFILES" | parallel --bar "$PYMCD $XMLFMT -i {}"
else
  for xmlfile in $XMLFILES; do
    $PYCMD $XMLFMT -i $xmlfile
    echo -n "."
  done
echo
fi

echo -e "\nDone"
exit 0
